# -*- coding: utf-8 -*-
from pprint import pprint

import requests


class DMClientConfig:
    def __init__(self, server_url, timeout=30):
        self.server_url = server_url
        self.timeout = timeout

class DMClient:
    def __init__(self, config):
        self.config = config
        self.session = requests.Session()
    
    def fetch_data(self, db_name, table_name, limit=10):
        """获取表数据"""
        url = f"{self.config.server_url}/api/data/fetch"
        payload = {
            "db_name": db_name,
            "table_name": table_name,
            "limit": limit
        }
        
        try:
            response = self.session.post(url, json=payload, timeout=self.config.timeout)
            response.raise_for_status()
            return response.json().get("data", [])
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return []
    
    def get_tables(self, db_name):
        """获取数据库表列表"""
        url = f"{self.config.server_url}/api/metadata/tables"
        params = {"db_name": db_name}
        
        try:
            response = self.session.get(url, params=params, timeout=self.config.timeout)
            response.raise_for_status()
            return response.json().get("tables", [])
        except requests.exceptions.RequestException as e:
            print(f"Error getting tables: {e}")
            return []
    
    def add_column(
        self,
        db_name,
        table_name,
        column_name,
        column_type,
        comment=None
    ):
        """添加表字段"""
        url = f"{self.config.server_url}/api/metadata/add-column"
        payload = {
            "db_name": db_name,
            "table_name": table_name,
            "column_name": column_name,
            "column_type": column_type
        }
        if comment:
            payload["comment"] = comment
        
        try:
            response = self.session.post(url, json=payload, timeout=self.config.timeout)
            response.raise_for_status()
            return True
        except requests.exceptions.RequestException as e:
            print(f"Error adding column: {e}")
            return False
    
    def add_comment(
        self,
        db_name,
        table_name,
        comment,
        column=None
    ):
        """添加注释"""
        url = f"{self.config.server_url}/api/metadata/add-comment"
        payload = {
            "db_name": db_name,
            "table_name": table_name,
            "comment": comment
        }
        if column:
            payload["column"] = column
        
        try:
            response = self.session.post(url, json=payload, timeout=self.config.timeout)
            response.raise_for_status()
            return True
        except requests.exceptions.RequestException as e:
            print(f"Error adding comment: {e}")
            return False

if __name__ == "__main__":
    # 示例用法
    config = DMClientConfig(server_url="http://10.200.58.71:8880")
    client = DMClient(config)
    
    # 获取表列表
    tables = client.get_tables("HY_ZGGL_DB")
    print("Tables:", tables)
    
    # 获取表数据
    data = client.fetch_data("HY_ZGGL_DB", "A01")
    pprint(data)
    
    # 添加字段
    success = client.add_column(
        db_name="HY_ZGGL_DB",
        table_name="A01",
        column_name="A1111",
        column_type="VARCHAR(100)",
        comment="测试字段"
    )
    print("Add column success:", success)
